package org.bioversityinternational.mgbms.model.dao;

import java.util.Random;

import org.apache.log4j.Logger;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.bioversityinternational.mgbms.model.dao.base.BaseDao;
import org.bioversityinternational.mgbms.model.domain.Address;
import org.bioversityinternational.mgbms.model.domain.Contact;
import org.bioversityinternational.mgbms.model.domain.Login;
import org.bioversityinternational.mgbms.model.domain.NewCentre;

@Component
public class LoginDao extends BaseDao<Login, Integer>
{
	private static final Logger LOG = Logger.getLogger(LoginDao.class);
	
	public LoginDao() {
		super(Login.class);		
        LOG.debug("LoginDao constructed");
	}

	@Override
	public Integer getIdFromString(String sIdAsString) {
		return Integer.parseInt(sIdAsString);
	}
		
	@Transactional(propagation=Propagation.SUPPORTS)
	public static Address getCorrectCentreAddressForUser(Login user)
	{
		NewCentre nc = user.getNewCentre();
		return nc != null ? nc.getAddress() : user.getContact().getAddress();
	}
		
	@Transactional(propagation=Propagation.SUPPORTS)
	public void generateRandomPassword(Login login, boolean fPersistChange)
	{
		login.setPassword(generateRandomPassword(8));
		if (fPersistChange)
			saveOrUpdate(login);
	}
}

